package cn.kongwg.contorller;

import cn.kongwg.entity.User;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author kongwg
 * @create 2021-03-08 22:50
 */
@RestController
public class JsonController {


    @RequestMapping("/json/j1")
    public String test() {
        Date date = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String s = sdf.format(date);

        String string = JSON.toJSONString(s);

        return string;

    }

    @RequestMapping("/json/j2")
    public String test2() {
        List<User> list = new ArrayList<>();
        User user1 = new User(1, "孔皮皮1", 18);
        User user2 = new User(1, "孔皮皮1", 18);
        User user3 = new User(1, "孔皮皮1", 18);

        list.add(user1);
        list.add(user2);
        list.add(user3);

        String string = JSON.toJSONString(list);

        return string;

    }

    @RequestMapping("/json/j3")
    public String test3() {
        List<User> list = new ArrayList<>();
        User user = new User(1, "孔皮皮1", 18);
        list.add(user);
        System.out.println("*******Java对象 转 JSON字符串*******");
        String str1 = JSON.toJSONString(list);
        System.out.println("JSON.toJSONString(list)==>" + str1);
        String str2 = JSON.toJSONString(user);
        System.out.println("JSON.toJSONString(user1)==>" + str2);

        System.out.println("\n****** JSON字符串 转 Java对象*******");
        User jp_user1 = JSON.parseObject(str2, User.class);
        System.out.println("JSON.parseObject(str2,User.class)==>" + jp_user1);

        System.out.println("\n****** Java对象 转 JSON对象 ******");
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user);
        System.out.println("(JSONObject) JSON.toJSON(user2)==>" + jsonObject1.getString("name"));

        System.out.println("\n****** JSON对象 转 Java对象 ******");
        User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
        System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>" + to_java_user);


        return str1;

    }


}
